package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.Account;
import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.exception.bank.ClientExistsException;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Class representing service methods to work with bank
 */
public class BankService {
    private BankService(){
    }
    /**
     * Adds client to bank
     * @param bank Bank
     * @param client Client to ba added
     */
    public static void addClient(Bank bank, Client client) throws ClientExistsException{
        bank.addClient(client);
    }

    /**
     * Returns collection of all accounts for specified bank
     * @param bank Bank to get accounts from
     * @return collection of all bank accounts
     */
    public static List<Account> getAllAccounts(Bank bank){
        List<Account> result = new ArrayList<Account>();
        for(Client c:bank.getAllClients()){
           if(c.getAccount()!=null){
                result.add(c.getAccount());
            }
        }
        return Collections.unmodifiableList(result);
    }

    /**
     * Establishes association between client and account
     * @param client client to associate
     * @param account account to associate
     */
    public static void associateClientWithAccount(Client client, Account account){
        client.setAccount(account);
        account.setClient(client);
    }
    /**
     * Unestablishes association between client and account
     * @param client client to disassociate
     * @param account account to disassociate
     */
    public static void disassociateClientWithAccount(Client client, Account account){
        if(account.equals(client.getAccount()) && client.equals(account.getClient())){
            client.setAccount(null);
            account.setClient(null);
        }else{
            throw new IllegalArgumentException("Client and account are not associated!");
        }
    }

}
